﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySpaceID_OpenId_OAuth.Core;
using MySpaceID.SDK;
using MySpaceID.SDK.OAuth.Tokens;
using MySpaceID.SDK.Context;
using MySpaceID.SDK.Api;

namespace MySpaceID_OpenId_OAuth.MembersOnly
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            PopulateUserProfile();
        }
        private void PopulateUserProfile()
        {
            if (State.OAuthOpenID != null)
            {
                var context = new OffsiteContext(Constants.ConsumerKey, Constants.ConsumerSecret);
                var verifier = Request.QueryString["oauth_verifier"];
                //Use the Request Token from the OpenID+OAuth extension to exchange for an Access Token.
                var accessToken = (AccessToken)context.GetAccessToken(State.OAuthOpenID.RequestToken, string.Empty, verifier);
                //Now that we have the Access Token, we set the following to properties to allow our class to make calls.
                context.OAuthTokenKey = accessToken.TokenKey;
                context.OAuthTokenSecret = accessToken.TokenSecret;
                //Get BasicProfile information of the logged in user.
                var myspaceClient = new RestV1(context);
                var user = myspaceClient.GetCurrentUser();
                var profile = myspaceClient.GetFullProfile(user.UserId);

                imageProfile.ImageUrl = user.Image;
                lblAge.Text = profile.Age.ToString();
                lblCity.Text = profile.City;
                lblCountry.Text = profile.Country;
                lblGender.Text = profile.Gender;
                lblMarital.Text = profile.MaritalStatus;
                lblName.Text = user.Name;
                lblPostalCode.Text = profile.Postalcode;
                lblProfileUrl.Text = user.WebUri;
                lblRegion.Text = profile.Region;

                PopulatePhotos(myspaceClient, user.UserId);
            }
            
        }

        private void PopulatePhotos(RestV1 myspaceClient, int userId)
        {
            var photos = myspaceClient.GetPhotos(userId);
            if (photos.Count > 0)
            {
                divPhotos.InnerHtml = "<ul>";
                foreach (var photo in photos.Photos)
                {
                    divPhotos.InnerHtml += string.Format("<li><img src='{0}' </></li>", photo.SmallImageUri);
                }
                divPhotos.InnerHtml += "</ul>";
            }
        }
    }
}
